define('OauthApi', [
  'UrlUtil',
  'BaseApi',
  'env'
], function (urlUtil, baseApi) {
  const URL_WX_WEB_OAUTH = "/wx_user/common/web_oauth2"
  const URL_WX_LOGIN = "/wx_user/common/login"
  const URL_TOKEN_REFRESH = "/wx_user/common/token_refresh"

  function _getWxOauthAuthorize() {
    let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WX_APPID + "&redirect_uri=" +
      encodeURI(location.href.split('#')[0]) + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    let code = urlUtil.getUrlParam("code");
    if (!code) {
      window.location.href = url;
    }
    return code;
  };

  function _wxOauth2(code) {
    let response = null;
    let url = BASE_URL + URL_WX_WEB_OAUTH;
    baseApi.get(url, {
      code: code
    }, {
      onSuccess: function (data) {
        response = data.data;
      },
      onError: function (errcode, errmsg) {
        console.error("获取微信openId失败", errmsg)
      }
    }, false);
    return response;
  };

  function _login(openid, callback) {
    let url = BASE_URL + URL_WX_LOGIN;
    baseApi.get(url, {
      openId: openid,
    }, {
      onSuccess: function (data) {
        callback.onSuccess(data)
      },
      onError: function (errcode, errmsg) {
        callback.onError(errcode, errmsg, openid)
      }

    })
  };

  function doWxLogin(callback) {
    let code = _getWxOauthAuthorize();
    if (!code) {
      return
    }
    let wxOauth2 = _wxOauth2(code);
    if (!wxOauth2) {
      return;
    }
    _login(wxOauth2.openId, callback);
  };

  function refreshToken(async, refreshToken, callback) {
    let url = BASE_URL + URL_TOKEN_REFRESH;
    baseApi.get(url, {
      refreshToken: refreshToken
    }, callback, async);
  };

  function getURLPaths() {
    return [URL_TOKEN_REFRESH, URL_WX_LOGIN, URL_WX_WEB_OAUTH];
  }

  return {
    doWxLogin: doWxLogin,
    refreshToken: refreshToken,
    getURLPaths: getURLPaths
  }
});